package com.dyz.swordFingerOffer;

import java.util.HashSet;

public class EntryNodeOfLoop23 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node3;
        new EntryNodeOfLoop23().EntryNodeOfLoop1(node1);
    }
    //HashSet
    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if(pHead==null){
            return pHead;
        }
        //创建Hashset
        HashSet<ListNode> set = new HashSet<>();
        ListNode cur = pHead;
        while (cur!=null){
            //如果hashset内有元素，添加元素返回结果为false
            boolean flag = set.add(cur);
            if(flag){//添加成功，表名不是环形链表的入口
                cur = cur.next;
            }else{

                return  cur;//否则时环形链表的入口
            }
        }
        return  null;
    }
    public ListNode EntryNodeOfLoop1(ListNode pHead) {
        //快慢指针
        if(pHead==null|| pHead.next == null){
            return null;
        }
        ListNode slow = pHead;
        ListNode fast = pHead;
        do{
            slow = slow.next;
            fast = fast.next.next;
        }while (slow!=fast);

        fast = pHead;
        while(slow!=fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
